﻿using Newtonsoft.Json;
using System;

namespace AbpProjectTemplate.Utilities.Json
{
    /// <summary>
    /// decimal保留两位小数的json转换器
    /// </summary>
    public class DecimalJsonConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(decimal) || objectType == typeof(decimal?);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.Value == null)
                return null;
            return Convert.ToDecimal(reader.Value);
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value == null)
                writer.WriteNull();
            else
            {
                var formated = decimal.Round(Convert.ToDecimal(value), 2); ;
                writer.WriteValue(formated);
            }
        }
    }
}


